const { findUserByUserIdAndRole, verifyPassword } = require('../models/user.model');
const jwt = require('jsonwebtoken');
const config = require('../config');
const ApiError = require('../utils/ApiError');

const login = async (req, res, next) => {
    try {
        const { username, password, role } = req.validatedData; // 使用验证后的数据

        // 查找用户
        const user = await findUserByUserIdAndRole(username, role);
        console.log("login() user:",user);
        if (!user) {
            throw new ApiError(401, "用户不存在或角色不匹配");
        }
        
        // 验证密码 (比较加密后的密码)
        if (!await verifyPassword(user, password)) {
            throw new ApiError(401, "密码错误");
        }
        
        // 创建JWT令牌
        const token = jwt.sign(
            { 
                id: user.userId, 
                userId: user.userId,
                role: role,
                name: user.name
            },
            config.jwt.secret, // 使用配置中的secret
            { expiresIn: config.jwt.expiresIn || '1h' } // 使用配置中的有效期
        );
        
        // 登录成功响应
        res.json({
            success: true,
            message: "登录成功",
            token,
            user: {
                userId: user.userId,
                role: role,
                name: user.name,
                email: user.email,
                class: user.class
            }
        });
        
    } catch (error) {
        next(error);
    }
};

module.exports = {
    login
};